package com.wlz.authorization.config;

import com.wlz.authorization.handler.MyAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 *  Authorization 授权
 *    访问控制的url匹配
 *      在配置类中http.authorizeRequests() 主要是对url进行控制。配置顺序会影响之后授权的效果，越是具
 *      体的应该放在前面，越是笼统的应该放到后面。
 * 2. regex 正则表达式
 */
//@Configuration
//@EnableWebSecurity 基于springboot 可以不用
public class WebSecurityRegexConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();  //表单登录

        //授权
        http.authorizeRequests()
                // regex 正则表达式
                //.regexMatchers(".+[.]jpg").permitAll() // 不用认证 所有以.jpg 结尾的文件都被放行
                .regexMatchers(HttpMethod.GET, ".+[.]jpg").permitAll()
                .anyRequest().authenticated();  // 必须认证

        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler()); // 支持自定义权限受限处理，需要实现 AccessDeniedHandler接口
        http.csrf().disable();//csrf关掉

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }


}
